<template>
  <el-dialog
    :visible="visible"
    :title="title"
    class="add-menu-dialog"
    align-center
    @opened="handleDialogOpen"
    @close="closeDialog"
    width="662px"
  >
    <el-form
      :model="menuForm"
      :rules="roleRules"
      ref="menuFormRef"
      label-width="120px"
    >
      <el-form-item label="菜单类型" prop="menuType">
        <el-radio-group
          v-model="menuForm.menuType"
          :disabled="menuForm.pkid ? true : false"
          @change="handleMenuTypeChange"
        >
          <el-radio :label="'0'">菜单</el-radio>
          <el-radio :label="'1'">按钮</el-radio>
          <!-- <Icon :data="selectIcon" :size="24" color="#124ebb"></Icon> -->
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentId">
        <el-cascader
          :options="menuOptions"
          v-model="menuForm.parentId"
          :props="props1"
          clearable
          placeholder="请选择"
          @change="handleParentMenuChange"
          :show-all-levels="false"
        />
      </el-form-item>
      <el-form-item
        label="菜单名称"
        prop="catalogName"
        v-if="menuForm.menuType === '0'"
      >
        <el-input v-model="menuForm.catalogName" />
      </el-form-item>
      <el-form-item label="按钮名称" prop="catalogName" v-else>
        <el-input v-model="menuForm.catalogName" />
      </el-form-item>
      <!--      <el-form-item-->
      <!--        label="菜单图标"-->
      <!--        prop="icon"-->
      <!--        v-if="menuForm.menuType === '1'"-->
      <!--      >-->
      <!--        <div class="icon-upload">-->
      <!--          <Vue3IconPicker-->
      <!--            v-model="menuForm.icon"-->
      <!--            placeholder="请选择"-->
      <!--            :clearable="true"-->
      <!--            iconLibrary="antd"-->
      <!--            value-type="name"-->
      <!--            :displaySearch="false"-->
      <!--          />-->
      <!--          <el-button @click="clickUpload">上传</el-button>-->
      <!--        </div>-->
      <!--      </el-form-item>-->
      <el-row v-if="menuForm.menuType === '0'">
        <el-col :span="12">
          <el-form-item label="已选中图标">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              accept="image/png, image/jpeg,image/jpg, image/gif"
              :on-change="handleFileChangeChoose"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageChooseUrl" :src="imageChooseUrl" class="avatar" />
            
              <!--              <el-icon v-else class="avatar-uploader-icon">-->
              <!--                <Plus />-->
              <!--              </el-icon>-->
              <i class="avatar-uploader-icon icon el-icon-plus" v-else>
              </i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="未选中图标">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              accept="image/png, image/jpeg,image/jpg, image/gif"
              :on-change="handleFileChangeUnChoose"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUnChooseUrl"
                :src="imageUnChooseUrl"
                class="avatar"
              />
              <!--              <el-icon v-else class="avatar-uploader-icon">-->
              <!--                <Plus />-->
              <!--              </el-icon>-->
              <i class="avatar-uploader-icon icon el-icon-plus" v-else></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="编码" prop="code">
        <el-input v-model="menuForm.code" />
      </el-form-item>
      <el-form-item label="地址" prop="routePath" v-if="menuForm.menuType === '0'">
        <el-input v-model="menuForm.routePath" />
      </el-form-item>
      <!-- <el-form-item label="重定向" prop="redirect">
        <el-input v-model="menuForm.redirect" />
      </el-form-item> -->
      <el-form-item
        label="菜单顺序"
        prop="orderIndex"
        v-if="menuForm.menuType === '0'"
      >
        <el-input-number v-model="menuForm.orderIndex" />
      </el-form-item>
      <!-- <el-form-item label="是否隐藏" prop="isShow">
        <el-radio-group v-model="menuForm.isShow">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="menuForm.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Message as ElMessage } from 'element-ui'
// import { Vue3IconPicker } from 'vue3-icon-picker'
// import "vue3-icon-picker/dist/style.css";
import { addMenuTree, updateMenuTree } from '@/api/back-management/menu'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  menuInfo: {
    type: Object,
    default: () => {},
  },
  parentMenuDict: {
    type: Array,
    default: () => [],
  },
  menuOptions: {
    type: Array,
    default: () => [],
  },
})

const props1 = {
  checkStrictly: true,
  label: 'catalogName',
  value: 'pkid',
}

const title = ref('新增菜单')

const emit = defineEmits(['closeDialog', 'updateMenu'])

const closeDialog = () => {
  emit('closeDialog')
}

const menuForm = reactive({
  menuType: '0',
  parentId: '',
  catalogName: '',
  icon: '',
  orderIndex: 0,
  status: 1,
  pkid: '',
  routePath: '',
  choosePicture: '',
  chooseSvgPicture: '',
  code: '',
  showStatus: 1,
})

const menuFormRef = ref()

const roleRules = reactive({
  menuType: [
    {
      required: true,
      message: '菜单类型不能为空',
      trigger: 'change',
    },
  ],
  parentId: [
    {
      required: true,
      message: '上级菜单不能为空',
      trigger: 'change',
    },
  ],
  catalogName: [
    {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    },
  ],
  routePath: [
    {
      required: true,
      message: '地址不能为空',
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '编码不能为空',
      trigger: 'blur',
    },
  ],
})

const imageChooseUrl = ref('')

const imageUnChooseUrl = ref('')

const chooseFile = ref()

const unChooseFile = ref()

const uploadFileShow = ref(false)

const handleParentMenuChange = (item: any) => {
  const val = item as string[]
  if (val) {
    menuForm.parentId = val[val.length - 1]
  } else {
    menuForm.parentId = ''
  }
}

const onSubmit = () => {
  menuFormRef.value?.validate((valid: any) => {
    if (valid) {
      let msg = ''
      menuForm.menuType === '0' ? (msg = '菜单') : (msg = '按钮')
      if (menuForm.pkid) {
        let params = null
        // if (chooseFile.value || unChooseFile.value) {
        //   params = new FormData()
        //   if (chooseFile.value) {
        //     params.append('chooseFile', chooseFile.value)
        //   }
        //   if (unChooseFile.value) {
        //     params.append('unChooseFile', unChooseFile.value)
        //   }
        // }
        if (imageChooseUrl.value) {
          menuForm.chooseSvgPicture = imageChooseUrl.value
        }
        if (imageUnChooseUrl.value) {
          menuForm.choosePicture = imageUnChooseUrl.value
        }
       
        // 删除图标
        if (!menuForm.icon) {
          menuForm.icon = ''
        }
        updateMenuTree(menuForm).then((res) => {
          if (res.success) {
            emit('updateMenu')
            ElMessage.success(`修改${msg}成功`)
          }
        })
      } else {
        if (
          (chooseFile.value && !unChooseFile.value) ||
          (!chooseFile.value && unChooseFile.value)
        ) {
          ElMessage.warning('请把选中、未选中图标上传完整')
          return
        }

        let params = null
        if (chooseFile.value && unChooseFile.value) {
          params = new FormData()
          params.append('chooseFile', chooseFile.value)
          params.append('unChooseFile', unChooseFile.value)
        }
        addMenuTree(menuForm).then((res) => {
          if (res.success) {
            emit('updateMenu')
            ElMessage.success(`添加${msg}成功`)
          }
        })
      }
    }
  })
}
const handleDialogOpen = () => {
  menuFormRef.value?.resetFields()
  if (props.menuInfo) {
    const {
      pkid,
      parentId,
      catalogName,
      icon,
      routePath,
      orderIndex,
      menuType,
      choosePicture,
      chooseSvgPicture,
      status,
      code,
    } = props.menuInfo
    menuForm.pkid = pkid || ''
    menuForm.parentId = parentId || ''
    menuForm.catalogName = catalogName || ''
    menuForm.routePath = routePath || ''
    menuForm.orderIndex = orderIndex || 0
    menuForm.menuType = menuType || '0'
    menuForm.icon = icon ? icon : ''
    imageChooseUrl.value = chooseSvgPicture ? chooseSvgPicture : ''
    imageUnChooseUrl.value = choosePicture ? choosePicture : ''
    menuForm.status = Number(status)
    menuForm.code = code || ''
    pkid ? (title.value = '编辑菜单') : (title.value = '新增菜单')
  }
}

const handleFileChangeChoose = (file: any) => {
  if (file.raw) {
    // imageChooseUrl.value = URL.createObjectURL(file.raw!)
    chooseFile.value = file.raw

    convertImageToBase64(file.raw).then((res) => {
      imageChooseUrl.value = res as string
    })
  }

  
}

const handleFileChangeUnChoose = (file: any) => {
  if (file.raw) {
    // imageUnChooseUrl.value = URL.createObjectURL(file.raw!)
    unChooseFile.value = file.raw

    convertImageToBase64(file.raw).then((res) => {
      imageUnChooseUrl.value = res as string
    })
  }
}

const isImage = (filename: string) => {
  const ext = filename.split('.').pop()!.toLowerCase() // Get the file extension in lowercase
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif'] // List of image extensions
  return imageExtensions.indexOf(ext) !== -1 // Check if the extension is in the list of image extensions
}

const beforeAvatarUpload = (rawFile: any) => {
  if (!isImage(rawFile.name)) {
    ElMessage.error('上传的文件必须是图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('上传的文件大小不能大于1M')
    return false
  }
  return true
}

const handleMenuTypeChange = () => {
  menuForm.menuType === '0'?
  menuFormRef.value?.validateField('routePath'):
  menuFormRef.value?.clearValidate('routePath')
}

const convertImageToBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

const clickUpload = () => {
  uploadFileShow.value = !uploadFileShow.value
}
</script>

<style lang="scss">
.add-menu-dialog {
  //width: 762px;
  //height: 623px;
  //background: #ffffff;
  border-radius: 4px;

  .el-dialog__body {
    padding-bottom: 0 !important;
  }

  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-form {
    margin-right: 40px;

    .el-form-item {
      min-height: 42px;
      margin-bottom: 21px;
      align-items: center;
    }

    .v3ip__custom-select .v3ip__items {
      z-index: 2;
    }

    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }

  .icon-upload {
    display: flex;
    align-items: center;

    .v3ip__custom-select {
      width: 490px;
      margin-right: 10px;
    }
  }

  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .avatar-uploader {
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }

      .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        text-align: center;
      }
    }
  }
}
</style>
